package com.matrix.im.infrastructure.event.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.matrix.api.marketing.MarketingApi;
import com.matrix.api.marketing.dto.DynamicCouponGrantDTO;
import com.matrix.api.merchant.MerchantApi;
import com.matrix.api.merchant.vo.ShopInfoVO;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author 有点甜
 * @since 2025/8/2
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CouponGrantingEventHandler {

    @DubboReference(check = false)
    private MarketingApi marketingApi;
    @DubboReference(check = false)
    private MerchantApi merchantApi;

    private final ObjectMapper objectMapper;

    @Async("imAsyncExecutor")
    public void handle(Long merchantUserId, Long customerUserId, String messageContent) {
        log.info("Handling dynamic coupon grant from merchant {} to customer {}", merchantUserId, customerUserId);
        try {
            ShopInfoVO shopInfo = merchantApi.getShopInfoByUserId(merchantUserId);
            if (shopInfo == null) {
                log.error("Cannot find shop info for merchant {}, coupon grant aborted.", merchantUserId);
                return;
            }
            Long shopId = shopInfo.getShopId();

            CouponJsonPayload payload = objectMapper.readValue(messageContent, CouponJsonPayload.class);

            DynamicCouponGrantDTO.CouponType type = "NO_THRESHOLD".equalsIgnoreCase(payload.getCouponType()) ?
                    DynamicCouponGrantDTO.CouponType.NO_THRESHOLD : DynamicCouponGrantDTO.CouponType.THRESHOLD;

            DynamicCouponGrantDTO grantDTO = DynamicCouponGrantDTO.builder()
                    .targetUserId(customerUserId)
                    .merchantUserId(merchantUserId)
                    .shopId(shopId)
                    .title(payload.getTitle())
                    .couponType(type)
                    .thresholdAmount(payload.getThresholdAmount())
                    .discountAmount(payload.getDiscountAmount())
                    .build();

            marketingApi.grantDynamicCouponByMerchant(grantDTO);
            log.info("Successfully granted dynamic coupon from shop {} to user {}.", shopId, customerUserId);

        } catch (Exception e) {
            log.error("Failed to grant dynamic coupon from merchant {}", merchantUserId, e);
        }
    }

    @Data
    private static class CouponJsonPayload {
        private String couponType;
        private String title;
        private BigDecimal thresholdAmount;
        private BigDecimal discountAmount;
    }
}